import { AppModel } from '../../../../model/AppModel'
import { createGPIOMenu } from '../BlockPackage'


export default {

    category: Blockly.Categories.control ,
    
    color: [
        Blockly.Colours.event.primary,
        Blockly.Colours.event.secondary,
        Blockly.Colours.event.tertiary
    ] ,

    previousStatement: false ,
    nextStatement: true ,

    eventHandle: true ,

    init(model: AppModel) {
        this.appendDummyInput()
                .appendField("当")
                .appendField(createGPIOMenu(model), 'stud')
                .appendField("输入")
                .appendField(new Blockly.FieldDropdown(() => {
                    return [
                        ['1 (上升沿)' , 'rise'] ,
                        ['0 (下降沿)' , 'fall'] ,
                    ]
                }), 'edge')
    } ,

    run (args: any, util: any, runtime: any) {
        return true
    } ,

    coder: {

        JavaScript(block: any, coder: any) {

            // console.log("event digital")

            let stud = block.getFieldValue('stud')
            let edge = block.getFieldValue('edge')
            let edgeName = edge=="rise"? '上升': '下降'

            let inner = ''
            let nextBlock = block.nextConnection && block.nextConnection.targetBlock()
            if(nextBlock) {
                coder.indent ++ 
                inner = coder.blockToCode(nextBlock)
                coder.indent --
            }

            return `${coder.indentString()}// 当颗粒 ${stud} 上的电平信号${edgeName}时\n`
                    + `pin(${stud}).watch(async ()=>{\n`
                    + inner
                    + `}, {mode: '${edge}'})\n`
        }
    }
}
